package com.leon.androidcoursedesign.ui.activitys.toolBoxActivity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.leon.androidcoursedesign.R;
import com.leon.androidcoursedesign.servers.MusicService;
import com.leon.androidcoursedesign.ui.activitys.BaseActivity;

public class MusicActivity extends BaseActivity implements SeekBar.OnSeekBarChangeListener {
    private static final int REQUEST_CODE = 1024;

    private SeekBar music_seekBar;
    private TextView music_textView_musicTitle, music_textView_nowProgress, music_textView_length;
    private ImageView music_circleImageView_cover;
    public static ImageView music_imageView_control;

    //music状态：0：停止(初始化状态)、1：正在播放、2：暂停状态
    public static int musicState = 0;

    //封面旋转动画
    public static ObjectAnimator rotation;

    //控制music
    private MusicService.MusicControl musicControl;

    //服务连接对象
    private MusicConnection musicConnection;

    //消息处理器
    public static Handler handler;

    private MediaMetadataRetriever metaRetriever;

    private Intent musicIntent;

    private Uri uri;
    private String title;
    private String duration;

    @Override
    public int setLayout() {
        return R.layout.activity_music;
    }

    @Override
    public void initView() {
        music_seekBar = findViewById(R.id.music_seekBar);
        music_seekBar.setOnSeekBarChangeListener(this);

        music_textView_musicTitle = findViewById(R.id.music_textView_musicTitle);
        music_textView_nowProgress = findViewById(R.id.music_textView_nowProgress);
        music_textView_length = findViewById(R.id.music_textView_length);

        music_circleImageView_cover = findViewById(R.id.music_imageView_cover);
        music_imageView_control = findViewById(R.id.music_imageView_control);
        music_imageView_control.setOnClickListener(this);

        this.setOnClick(R.id.music_imageView_back).setOnClick(R.id.music_imageView_openFile);
    }

    @Override
    public void initValue() {
        //设置旋转动画
        rotation = ObjectAnimator.ofFloat(music_circleImageView_cover, "rotation", 0.0f, 360.0f);
        rotation.setDuration(45000);//一圈的时间
        rotation.setInterpolator(new LinearInterpolator());
        rotation.setRepeatCount(-1);//次数，-1为无限制
        rotation.setRepeatMode(ObjectAnimator.RESTART);//动画始终重复

        music_textView_nowProgress.setText("00:00");

        if (uri != null) {
            String musicDuration = getMusicDuration(uri);
            music_textView_length.setText(musicDuration);
        } else {
            music_textView_length.setText("00:00");
        }

        if (uri != null) {
            title = getMusicName(uri);
            music_textView_musicTitle.setText(title);

            duration = getMusicDuration(uri);
            music_textView_length.setText(duration);
        } else {
            music_textView_musicTitle.setText("歌曲还未选择");
        }

        musicConnection = new MusicConnection();
        musicIntent = new Intent(this, MusicService.class);

        //绑定服务
        bindService(musicIntent, musicConnection, Context.BIND_AUTO_CREATE);

        //处理消息
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                Bundle bundle = msg.getData();

                //获取总长度
                int duration = bundle.getInt("duration");

                //获取当前进度
                int currentPosition = bundle.getInt("currentPosition");

                //设置进度条最大值
                music_seekBar.setMax(duration);

                //设置进度条当前进度
                music_seekBar.setProgress(currentPosition);

                int minute = currentPosition / 1000 / 60;
                int second = currentPosition / 1000 % 60;

                String length = (minute < 10 ? "0" + minute : minute + "") + ":" + (second < 10 ? "0" + second : second + "");

                //设置时间进度
                music_textView_nowProgress.setText(length);

                return true;
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.music_imageView_back:
                this.finish();
                break;
            case R.id.music_imageView_openFile:
                openFileManager();
                break;
            case R.id.music_imageView_control:
                if (uri == null) {
                    Toast.makeText(this, "请选择音频文件后再进行播放", Toast.LENGTH_SHORT).show();
                    break;
                }

                switch (musicState) {
                    case 0:
                        //动画开始
                        rotation.start();
                        musicState = 1;
                        music_imageView_control.setImageResource(R.drawable.music_icon_play);

                        //设置播放地址并播放音乐
                        musicControl.play(this.uri);

                        break;
                    case 1:
                        //动画暂停
                        rotation.pause();
                        musicState = 2;
                        music_imageView_control.setImageResource(R.drawable.music_icon_pause);

                        //暂停音乐
                        musicControl.pause();

                        break;
                    case 2:
                        //动画继续
                        rotation.resume();
                        musicState = 1;
                        music_imageView_control.setImageResource(R.drawable.music_icon_play);

                        //继续播放音乐
                        musicControl.continuePlay();

                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }

    private void openFileManager() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/mpeg");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                this.uri = uri;
                switchMusic(uri);
            }
        }
    }

    /**
     * 获取歌曲名称
     *
     * @param uri   歌曲uri
     * @return  返回歌曲名称
     */
    private String getMusicName(Uri uri) {
        final  String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};

        Cursor cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToNext()) {
            int columnIndex = cursor.getColumnIndex(projection[0]);

            String string = cursor.getString(columnIndex);
            cursor.close();
            return string;
        }

        if (cursor != null) {
            cursor.close();
        }

        return null;
    }

    /**
     * 获取歌曲长度
     *
     * @param uri   歌曲uri
     * @return  返回歌曲长度
     */
    private String getMusicDuration(Uri uri) {
        if (metaRetriever == null) {
            metaRetriever = new MediaMetadataRetriever();
        }

        metaRetriever.setDataSource(getApplicationContext(), uri);
        String extractMetadata = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long duration = Long.parseLong(extractMetadata);

        long minute = duration / 60000;
        long second = (duration % 60000) / 1000;

        String minuteStr = minute < 10 ? "0" + minute : String.valueOf(minute);
        String secondStr = second < 10 ? "0" + second : String.valueOf(second);

        return minuteStr + ":" + secondStr;
    }

    /**
     * 切换歌曲
     *
     * @param uri   音频uri
     */
    private void switchMusic(Uri uri) {
        //暂停音乐
        musicControl.pause();

        //暂停当前动画
        rotation.pause();

        //设置当前歌曲状态为正在播放
        musicState = 1;
        music_imageView_control.setImageResource(R.drawable.music_icon_play);

        //播放音乐
        musicControl.play(uri);

        //刷新当前activity上的数据
        initValue();

        //开始动画
        rotation.start();
    }

    /**
     * 开启服务
     */
    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * 停止服务
     */
    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * Activity的销毁
     */
    @Override
    protected void onDestroy() {
        unbind();
        musicState = 0;
        super.onDestroy();
    }

    /**
     * 解绑服务
     */
    public void unbind() {
        musicControl.pause();

        //解绑服务
        unbindService(musicConnection);

        //停止服务
        stopService(musicIntent);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    /**
     * 离开seekBar时的监听
     *
     * @param seekBar seekBar对象
     */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        musicControl.seekPlayProgress(progress);
    }

    //服务连接类
    class MusicConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicControl = (MusicService.MusicControl) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}